/**
 * EduVerse Credentials - 发行方门户模块
 * 
 * 实现发行方门户的核心功能，包括发行方DID管理、VC Schema管理、凭证发行和撤销管理等。
 * 注意：这是一个简化的后端API实现，实际项目中可能需要前端UI组件。
 */

const express = require('express');
const { initPolygonIdSDK } = require('../utils/sdk-init');
const { initMockSDK } = require('../utils/sdk-mock');
const { 
  createPolygonIdIdentity, 
  publishPolygonIdState 
} = require('../core/did');
const { 
  issueCredentialWithPolygonId, 
  addDataIntegrityProof 
} = require('../core/vc');
const { 
  BitstringStatusListManager, 
  Iden3RevocationManager 
} = require('../core/revocation');
const { v4: uuidv4 } = require('uuid');
const fs = require('fs');
const path = require('path');

// 数据文件路径
const ISSUER_DATA_DIR = path.join(__dirname, '..', '..', 'data', 'issuer');
const ISSUER_DID_FILE = path.join(ISSUER_DATA_DIR, 'issuerDid.json');
const SCHEMAS_FILE = path.join(ISSUER_DATA_DIR, 'schemas.json');
const ISSUED_CREDENTIALS_FILE = path.join(ISSUER_DATA_DIR, 'issued_credentials.json');

// 确保数据目录存在
if (!fs.existsSync(ISSUER_DATA_DIR)) {
  fs.mkdirSync(ISSUER_DATA_DIR, { recursive: true });
}

/**
 * 从JSON文件加载数据 (与wallet/index.js中的函数类似，但为避免循环依赖等问题，这里重新定义)
 */
function loadDataFromFile(filePath, isMap = true) {
  try {
    if (fs.existsSync(filePath)) {
      const fileData = fs.readFileSync(filePath, 'utf-8');
      if (fileData) {
        const parsedData = JSON.parse(fileData);
        if (isMap) {
          if (Array.isArray(parsedData)) return new Map(parsedData);
          return new Map(Object.entries(parsedData)); // 兼容旧格式
        }
        // 对于 issuerDID，确保它有一个 string() 方法
        if (filePath.endsWith('issuerDid.json') && parsedData && typeof parsedData.id === 'string') {
          return {
            id: parsedData.id, // 假设普通对象至少有id字段
            string: function() { return this.id; },
            // 如果原始对象中有authCredential，也一并保留
            ...(parsedData.authCredential && { authCredential: parsedData.authCredential })
          };
        }
        return parsedData; // 直接返回对象
      }
    }
  } catch (error) {
    console.error(`从 ${filePath} 加载数据失败:`, error);
  }
  return isMap ? new Map() : null; // 如果不是Map且加载失败，返回null
}

/**
 * 将数据保存到JSON文件 (与wallet/index.js中的函数类似)
 */
function saveDataToFile(filePath, data, isMap = true) {
  try {
    let dataToSave = data;
    if (isMap) {
      dataToSave = Array.from(data.entries());
    } else if (filePath.endsWith('issuerDid.json') && data && typeof data.string === 'function') {
      // 对于 issuerDID，保存一个更纯净的对象，移除函数等不可序列化的部分，但保留核心信息
      dataToSave = {
        id: data.string(), // 调用string()获取ID
        ...(data.authCredential && { authCredential: data.authCredential })
        // 如果还有其他需要持久化的字段，在这里添加
      };
    }
    fs.writeFileSync(filePath, JSON.stringify(dataToSave, null, 2), 'utf-8');
  } catch (error) {
    console.error(`保存数据到 ${filePath} 失败:`, error);
  }
}

class IssuerApp {
  constructor() {
    this.app = express();
    this.router = express.Router();
    this.sdkComponents = null;
    this.issuerStorage = {};
    
    this.setupRoutes();
  }
  
  /**
   * 初始化发行方应用
   */
  async initialize(config = {}) {
    try {
      console.log("Initializing issuer app...");
      
      // 初始化发行方存储 - 现在从文件加载
      this.issuerStorage = {
        issuerDID: loadDataFromFile(ISSUER_DID_FILE, false),
        schemas: loadDataFromFile(SCHEMAS_FILE),
        credentials: loadDataFromFile(ISSUED_CREDENTIALS_FILE),
        statusListManager: null, // 这个保持原样，它有自己的持久化
        iden3RevocationManager: null
      };
      
      try {
        // 尝试初始化真实SDK
        this.sdkComponents = await initPolygonIdSDK(config);
      } catch (sdkError) {
        // 如果真实SDK初始化失败，使用模拟SDK
        console.warn("使用模拟SDK进行开发...", sdkError.message);
        this.sdkComponents = await initMockSDK(config);
        this._usingMockSdk = true;
      }
      
      // 确保 this.sdkComponents 和 this.sdkComponents.dataStorage 已定义
      if (!this.sdkComponents || !this.sdkComponents.dataStorage) {
        console.error("关键SDK组件 (sdkComponents 或 dataStorage) 未初始化!");
        throw new Error("关键SDK组件未初始化");
      }
      
      // 设置W3C Bitstring Status List管理器
      const statusListConfig = {
        storageDir: path.join(config.dataStoragePath || './data', 'status-lists'),
        baseUrl: config.statusListBaseUrl || process.env.STATUS_LIST_BASE_URL || 'http://localhost:3000/credentials/status',
        issuerDidUrl: null, // 初始为null，创建DID后再更新
        issuerKeyPair: {} // 简化: 实际实现中应提供正确的密钥对
      };
      
      this.issuerStorage.statusListManager = new BitstringStatusListManager(statusListConfig);
      await this.issuerStorage.statusListManager.initialize();
      
      this.app.use(express.json());
      this.app.use('/api/issuer', this.router);
      
      // 状态列表访问路由
      this.app.get('/credentials/status/:listId', this.getStatusList.bind(this));
      
      // 自动创建默认发行方DID (如果文件中没有)
      try {
        if (!this.issuerStorage.issuerDID) {
          console.log("正在创建默认发行方DID (因为文件中未找到)...");
          const { identityWallet } = this.sdkComponents;
          const { did, authCredential } = await createPolygonIdIdentity(identityWallet);
          
          this.issuerStorage.issuerDID = did; // did 对象应该包含 string() 方法
          saveDataToFile(ISSUER_DID_FILE, this.issuerStorage.issuerDID, false);
          
          // 更新状态列表管理器的发行方DID
          if (this.issuerStorage.statusListManager) {
            this.issuerStorage.statusListManager.issuerDidUrl = did.string();
          }
          
          // 创建Iden3 SMT撤销管理器
          this.issuerStorage.iden3RevocationManager = new Iden3RevocationManager({
            identityWallet,
            proofService: this.sdkComponents.proofService,
            issuerDID: did
          });
          
          console.log("创建了默认发行方DID:", did.string());
        }
      } catch (didError) {
        console.warn("无法创建默认发行方DID:", didError.message);
        // 继续初始化，用户可以稍后手动创建DID
      }
      
      console.log("Issuer app initialized");
      return this;
    } catch (error) {
      console.error("Error initializing issuer app:", error);
      throw error;
    }
  }
  
  /**
   * 设置API路由
   */
  setupRoutes() {
    // 健康检查端点
    this.router.get('/health', (req, res) => {
      res.json({ 
        status: 'ok', 
        timestamp: new Date().toISOString(),
        usingMockSdk: this._usingMockSdk 
      });
    });
    
    // 添加示例数据加载路由
    this.router.post('/load-samples', this.loadSampleCredentials.bind(this));
    this.router.post('/schemas/load-samples', this.loadSampleSchemas.bind(this));
    
    // DID管理相关路由
    this.router.post('/dids/create', this.createIssuerIdentity.bind(this));
    this.router.get('/dids/current', this.getCurrentIssuerDID.bind(this));
    this.router.post('/dids/publish-state', this.publishIssuerState.bind(this));
    
    // Schema管理相关路由
    this.router.post('/schemas', this.createSchema.bind(this));
    this.router.get('/schemas', this.listSchemas.bind(this));
    this.router.get('/schemas/:id', this.getSchema.bind(this));
    
    // 凭证发行相关路由
    this.router.post('/credentials/issue', this.issueCredential.bind(this));
    this.router.get('/credentials', this.listCredentials.bind(this));
    
    // 凭证撤销相关路由
    this.router.post('/credentials/:id/revoke', this.revokeCredential.bind(this));
  }
  
  /**
   * 启动服务
   */
  start(port = process.env.PORT || 3000) {
    return new Promise((resolve) => {
      const server = this.app.listen(port, () => {
        console.log(`Issuer app listening on port ${port}`);
        resolve(server);
      });
    });
  }
  
  /**
   * 创建发行方身份
   */
  async createIssuerIdentity(req, res) {
    try {
      const { identityWallet } = this.sdkComponents;
      const { did, authCredential } = await createPolygonIdIdentity(identityWallet);
      
      this.issuerStorage.issuerDID = did; // did 对象应该包含 string() 方法
      saveDataToFile(ISSUER_DID_FILE, this.issuerStorage.issuerDID, false);
      
      if (this.issuerStorage.statusListManager) {
        this.issuerStorage.statusListManager.issuerDidUrl = did.string();
      }
      
      // 创建Iden3 SMT撤销管理器
      this.issuerStorage.iden3RevocationManager = new Iden3RevocationManager({
        identityWallet,
        proofService: this.sdkComponents.proofService,
        issuerDID: did
      });
      
      res.status(201).json({
        success: true,
        issuerDID: did.string()
      });
    } catch (error) {
      console.error("Error creating issuer identity:", error);
      res.status(500).json({
        success: false,
        error: error.message
      });
    }
  }
  
  /**
   * 获取当前发行方DID
   */
  getCurrentIssuerDID(req, res) {
    try {
      if (!this.issuerStorage.issuerDID) {
        return res.status(404).json({
          success: false,
          error: "Issuer DID not created yet"
        });
      }
      
      res.status(200).json({
        success: true,
        issuerDID: this.issuerStorage.issuerDID.string()
      });
    } catch (error) {
      console.error("Error getting current issuer DID:", error);
      res.status(500).json({
        success: false,
        error: error.message
      });
    }
  }
  
  /**
   * 发布发行方状态到链上
   */
  async publishIssuerState(req, res) {
    try {
      if (!this.issuerStorage.issuerDID) {
        return res.status(404).json({
          success: false,
          error: "Issuer DID not created yet"
        });
      }
      
      const { identityWallet, proofService, dataStorage, ethSigner } = this.sdkComponents;
      const rhsUrl = req.body.rhsUrl || process.env.RHS_URL;
      
      const txResult = await publishPolygonIdState(
        identityWallet,
        proofService,
        this.issuerStorage.issuerDID,
        dataStorage,
        ethSigner,
        rhsUrl
      );
      
      res.status(200).json({
        success: true,
        transactionHash: txResult.hash
      });
    } catch (error) {
      console.error("Error publishing issuer state:", error);
      res.status(500).json({
        success: false,
        error: error.message
      });
    }
  }
  
  /**
   * 创建凭证Schema
   */
  async createSchema(req, res) {
    try {
      const { name, description, type, attributes, context } = req.body;
      
      if (!name || !type || !attributes) {
        return res.status(400).json({
          success: false,
          error: "name, type and attributes are required"
        });
      }
      
      // 生成Schema ID
      const schemaId = `schema-${uuidv4()}`;
      
      // 创建Schema对象
      const schema = {
        id: schemaId,
        name,
        description,
        type,
        attributes,
        context: context || `https://eduverse.example.com/schemas/${type.toLowerCase()}.jsonld`,
        created: new Date().toISOString()
      };
      
      this.issuerStorage.schemas.set(schemaId, schema);
      saveDataToFile(SCHEMAS_FILE, this.issuerStorage.schemas); // 保存到文件
      
      // 在实际实现中，可能需要持久化Schema或发布到IPFS
      
      res.status(201).json({
        success: true,
        schema
      });
    } catch (error) {
      console.error("Error creating schema:", error);
      res.status(500).json({
        success: false,
        error: error.message
      });
    }
  }
  
  /**
   * 列出所有Schema
   */
  listSchemas(req, res) {
    try {
      const schemas = Array.from(this.issuerStorage.schemas.values());
      
      res.status(200).json({
        success: true,
        schemas
      });
    } catch (error) {
      console.error("Error listing schemas:", error);
      res.status(500).json({
        success: false,
        error: error.message
      });
    }
  }
  
  /**
   * 获取Schema详情
   */
  getSchema(req, res) {
    try {
      const { id } = req.params;
      
      const schema = this.issuerStorage.schemas.get(id);
      
      if (!schema) {
        return res.status(404).json({
          success: false,
          error: "Schema not found"
        });
      }
      
      res.status(200).json({
        success: true,
        schema
      });
    } catch (error) {
      console.error("Error getting schema:", error);
      res.status(500).json({
        success: false,
        error: error.message
      });
    }
  }
  
  /**
   * 发行凭证
   */
  async issueCredential(req, res) {
    try {
      const { 
        schemaId, 
        subjectDid, 
        attributes, 
        expirationDate, 
        useW3CStatusList = true,
        statusListId = 'default'
      } = req.body;
      
      if (!this.issuerStorage.issuerDID || typeof this.issuerStorage.issuerDID.string !== 'function') {
        console.error("发行方DID无效或未正确加载:", this.issuerStorage.issuerDID);
        return res.status(400).json({
          success: false,
          error: "Issuer DID not created yet or not loaded correctly.",
          suggestion: "请尝试重新创建发行方身份或检查服务器日志。"
        });
      }
      
      if (!schemaId || !subjectDid || !attributes) {
        return res.status(400).json({
          success: false,
          error: "schemaId, subjectDid and attributes are required"
        });
      }
      
      // 获取Schema
      const schema = this.issuerStorage.schemas.get(schemaId);
      if (!schema) {
        // 如果没有已保存的模式，创建一个默认模式
        if (this.issuerStorage.schemas.size === 0) {
          console.log("没有找到Schema，创建一个默认Schema");
          const defaultSchemaId = `schema-${uuidv4()}`;
          const defaultSchema = {
            id: defaultSchemaId,
            name: "默认凭证模板",
            description: "自动创建的默认凭证模板",
            type: "DefaultCredential",
            attributes: Object.keys(attributes).reduce((acc, key) => {
              acc[key] = typeof attributes[key];
              return acc;
            }, {}),
            context: `https://eduverse.example.com/schemas/default.jsonld`,
            created: new Date().toISOString()
          };
          
          this.issuerStorage.schemas.set(defaultSchemaId, defaultSchema);
          console.log(`创建了默认Schema: ${defaultSchemaId}`);
          
          return res.status(400).json({
            success: false,
            error: `Schema ${schemaId} not found`,
            suggestion: `已创建默认Schema ${defaultSchemaId}，请使用此ID重新发行凭证`,
            defaultSchemaId
          });
        } else {
          // 如果有其他模式，建议使用已存在的模式
          const availableSchemas = Array.from(this.issuerStorage.schemas.entries())
            .map(([id, s]) => ({ id, name: s.name }));
          
          return res.status(404).json({
            success: false,
            error: `Schema ${schemaId} not found`,
            suggestion: "请使用以下可用的Schema之一",
            availableSchemas
          });
        }
      }
      
      console.log(`使用模式 ${schemaId} 发行凭证给 ${subjectDid}`);
      console.log(`属性: ${JSON.stringify(attributes)}`);
      
      try {
        // 准备凭证数据
        const credentialData = {
          credentialSchema: schema.context,
          type: schema.type,
          credentialSubject: {
            id: subjectDid,
            ...attributes
          },
          expiration: expirationDate
        };
        
        // 使用Polygon ID SDK发行凭证
        const { identityWallet } = this.sdkComponents;
        
        if (!identityWallet) {
          return res.status(500).json({
            success: false,
            error: "Identity wallet not initialized",
            suggestion: "请确保SDK正确初始化"
          });
        }
        
        console.log(`使用发行方DID: ${this.issuerStorage.issuerDID.string()}`);
        
        const credential = await issueCredentialWithPolygonId(
          identityWallet, 
          this.issuerStorage.issuerDID, // 现在这个应该有 string() 方法
          credentialData
        );
        
        const credentialId = credential.id || `credential-${uuidv4()}`;
        const storedCredentialData = {
          id: credentialId,
          schemaId: req.body.schemaId, // 从请求中获取schemaId
          subjectDid: req.body.subjectDid,
          issuanceDate: credential.issuanceDate,
          expirationDate: credential.expirationDate,
          credential, // 存储完整凭证
          revoked: false
        };
        this.issuerStorage.credentials.set(credentialId, storedCredentialData);
        saveDataToFile(ISSUED_CREDENTIALS_FILE, this.issuerStorage.credentials); // 保存到文件
        
        // 如果使用W3C Bitstring Status List，添加状态信息
        let updatedCredential = credential;
        if (useW3CStatusList && this.issuerStorage.statusListManager) {
          // 分配状态索引
          const statusInfo = await this.issuerStorage.statusListManager.assignStatusIndex(
            credentialId,
            statusListId
          );
          
          // 添加状态信息到凭证
          updatedCredential = {
            ...credential,
            credentialStatus: {
              id: statusInfo.statusId,
              type: "BitstringStatusList2021Status",
              statusListIndex: statusInfo.index.toString(),
              statusListCredential: statusInfo.statusUrl
            }
          };
        }
        
        // 在实际实现中，可能需要添加Data Integrity证明
        // updatedCredential = await addDataIntegrityProof(updatedCredential, ...);
        
        // 更新存储的凭证
        this.issuerStorage.credentials.get(credentialId).credential = updatedCredential;
        
        res.status(201).json({
          success: true,
          credentialId,
          credential: updatedCredential
        });
      } catch (issueError) {
        console.error("凭证发行过程中出错:", issueError);
        res.status(500).json({
          success: false,
          error: `发行凭证时出错: ${issueError.message}`,
          details: issueError.stack
        });
      }
    } catch (error) {
      console.error("Error issuing credential:", error);
      res.status(500).json({
        success: false,
        error: error.message
      });
    }
  }
  
  /**
   * 列出所有发行的凭证
   */
  listCredentials(req, res) {
    try {
      const credentials = Array.from(this.issuerStorage.credentials.values()).map(cred => ({
        id: cred.id,
        schemaId: cred.schemaId,
        subjectDid: cred.subjectDid,
        issuanceDate: cred.issuanceDate,
        expirationDate: cred.expirationDate,
        revoked: cred.revoked
      }));
      
      res.status(200).json({
        success: true,
        credentials
      });
    } catch (error) {
      console.error("Error listing credentials:", error);
      res.status(500).json({
        success: false,
        error: error.message
      });
    }
  }
  
  /**
   * 撤销凭证
   */
  async revokeCredential(req, res) {
    try {
      const { id } = req.params;
      const { method = 'w3c-status-list' } = req.body; // 'w3c-status-list' or 'iden3-smt'
      
      const credInfo = this.issuerStorage.credentials.get(id);
      if (!credInfo) {
        return res.status(404).json({
          success: false,
          error: "Credential not found"
        });
      }
      
      if (credInfo.revoked) {
        return res.status(400).json({
          success: false,
          error: "Credential already revoked"
        });
      }
      
      let revocationResult;
      
      if (method === 'w3c-status-list') {
        // 使用W3C Bitstring Status List撤销
        revocationResult = await this.issuerStorage.statusListManager.revokeCredential(id);
      } else if (method === 'iden3-smt') {
        // 使用Polygon ID Iden3 SMT撤销
        if (!this.issuerStorage.iden3RevocationManager) {
          return res.status(400).json({
            success: false,
            error: "Iden3 revocation manager not initialized"
          });
        }
        
        revocationResult = await this.issuerStorage.iden3RevocationManager.revokeCredential(
          credInfo.credential,
          this.sdkComponents.ethSigner,
          this.sdkComponents.dataStorage
        );
      } else {
        return res.status(400).json({
          success: false,
          error: "Invalid revocation method"
        });
      }
      
      if (revocationResult && (revocationResult === true || revocationResult.success)) {
        // 更新凭证状态
        credInfo.revoked = true;
        this.issuerStorage.credentials.set(id, credInfo);
        saveDataToFile(ISSUED_CREDENTIALS_FILE, this.issuerStorage.credentials); // 保存更新后的凭证状态
        
        res.status(200).json({
          success: true,
          credentialId: id,
          revoked: true,
          method,
          result: revocationResult
        });
      } else {
        res.status(500).json({
          success: false,
          error: "Failed to revoke credential",
          result: revocationResult
        });
      }
    } catch (error) {
      console.error("Error revoking credential:", error);
      res.status(500).json({
        success: false,
        error: error.message
      });
    }
  }
  
  /**
   * 获取状态列表
   */
  async getStatusList(req, res) {
    try {
      const { listId } = req.params;
      
      const statusList = await this.issuerStorage.statusListManager.getStatusList(listId);
      
      res.status(200).json(statusList);
    } catch (error) {
      console.error(`Error retrieving status list ${req.params.listId}:`, error);
      
      if (error.code === 'ENOENT') {
        res.status(404).json({
          error: "Status list not found"
        });
      } else {
        res.status(500).json({
          error: "Internal server error"
        });
      }
    }
  }
  
  /**
   * 加载示例Schema数据
   */
  async loadSampleSchemas(req, res) {
    try {
      console.log("加载示例Schema数据...");
      
      // 加载示例Schema
      const sampleSchemasPath = path.join(__dirname, '..', '..', '..', 'data', 'sample-schemas.json');
      let sampleSchemas = [];
      
      if (fs.existsSync(sampleSchemasPath)) {
        console.log(`找到示例Schema文件: ${sampleSchemasPath}`);
        sampleSchemas = JSON.parse(fs.readFileSync(sampleSchemasPath, 'utf-8'));
      } else {
        console.log(`示例Schema文件不存在: ${sampleSchemasPath}`);
        return res.status(404).json({
          success: false,
          error: "示例Schema文件不存在"
        });
      }
      
      // 导入示例Schema
      const results = [];
      for (const schema of sampleSchemas) {
        try {
          // 检查Schema是否已存在
          if (this.issuerStorage.schemas.has(schema.id)) {
            console.log(`Schema已存在，跳过: ${schema.id}`);
            continue;
          }
          
          // 添加Schema到存储
          this.issuerStorage.schemas.set(schema.id, schema);
          
          results.push({
            id: schema.id,
            name: schema.name,
            type: schema.type
          });
        } catch (error) {
          console.error(`处理示例Schema ${schema.id} 时出错:`, error);
        }
      }
      
      // 保存更新后的Schema存储
      saveDataToFile(SCHEMAS_FILE, this.issuerStorage.schemas);
      
      res.status(200).json({
        success: true,
        message: `成功加载 ${results.length} 个示例Schema`,
        schemas: results
      });
    } catch (error) {
      console.error("加载示例Schema失败:", error);
      res.status(500).json({
        success: false,
        error: `加载示例Schema失败: ${error.message}`
      });
    }
  }
  
  /**
   * 加载示例凭证数据
   */
  async loadSampleCredentials(req, res) {
    try {
      console.log("加载示例凭证数据...");
      
      // 加载示例凭证
      const sampleCredentialsPath = path.join(__dirname, '..', '..', '..', 'data', 'sample-credentials.json');
      let sampleCredentials = [];
      
      if (fs.existsSync(sampleCredentialsPath)) {
        console.log(`找到示例凭证文件: ${sampleCredentialsPath}`);
        sampleCredentials = JSON.parse(fs.readFileSync(sampleCredentialsPath, 'utf-8'));
      } else {
        console.log(`示例凭证文件不存在: ${sampleCredentialsPath}`);
        return res.status(404).json({
          success: false,
          error: "示例凭证文件不存在"
        });
      }
      
      // 为每个示例创建凭证
      const results = [];
      for (const sample of sampleCredentials) {
        try {
          // 为示例数据添加基本凭证字段
          const credential = {
            id: `urn:uuid:${uuidv4()}`,
            type: ["VerifiableCredential", sample.type],
            issuer: this.issuerStorage.issuerDID ? this.issuerStorage.issuerDID.string() : "did:example:issuer",
            issuanceDate: new Date().toISOString(),
            expirationDate: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString(), // 一年后过期
            credentialSubject: sample.data.credentialSubject
          };
          
          // 添加凭证到存储
          const credentialId = credential.id;
          this.issuerStorage.credentials.set(credentialId, {
            credential,
            holderDID: credential.credentialSubject.id,
            issuerDID: credential.issuer,
            status: "active",
            issuanceDate: credential.issuanceDate,
            expirationDate: credential.expirationDate,
            revoked: false
          });
          
          results.push({
            credentialId,
            type: sample.type,
            description: sample.description,
            subject: credential.credentialSubject.id
          });
        } catch (sampleError) {
          console.error(`处理示例 ${sample.type} 时出错:`, sampleError);
        }
      }
      
      // 保存更新后的凭证存储
      saveDataToFile(ISSUED_CREDENTIALS_FILE, this.issuerStorage.credentials);
      
      res.status(200).json({
        success: true,
        message: `成功加载 ${results.length} 个示例凭证`,
        credentials: results
      });
    } catch (error) {
      console.error("加载示例凭证失败:", error);
      res.status(500).json({
        success: false,
        error: `加载示例凭证失败: ${error.message}`
      });
    }
  }
}

module.exports = IssuerApp; 